package fr.gmdev.mail.fonction.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import fr.gmdev.mail.fonction.alfresco.ContentReadAndWrite;
import fr.gmdev.mail.fonction.mail.MailMessage;
import fr.gmdev.mail.fonction.mail.PieceJointe;
import fr.gmdev.mail.fonction.mail.SMTPManager;
import fr.gmdev.mail.fonction.mailet.MailetGmdev;
import fr.gmdev.mail.fonction.sms.SMSManager;
import fr.gmdev.mail.util.MailetLogger;

public class LocalWorkFlowManager {

	private SMTPManager smtpManager ;
	
	private SMSManager smsManager;
	
	private MailetLogger logger;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy  hh:mm");

	public LocalWorkFlowManager() {
		super();
	}
	public LocalWorkFlowManager(SMTPManager smtpManager, SMSManager smsManager) {
		this();
		this.smtpManager = smtpManager;
		this.smsManager = smsManager;
	}
	

	public void traiterMail  (MimeMessage message) throws Exception{
		
		String sujet = message.getSubject();
		if (sujet != null ){
			sujet = sujet.trim().toLowerCase();
			if (sujet.startsWith("action=")){
				
				// traitement des actions
				log("sujet=" + sujet);
				traiterActions(sujet,message);
			}
		}else{
			System.out.println("WARN: Sujet null");
		}
	}

	public void traiterActions(String sujet,MimeMessage message) throws Exception {
		String actionString = sujet.substring(7);
		String[] actions = actionString.split(",");
		for (String action : actions) {
			log("traitement de l'action:" + action);
			traiterActionUnitaite(action, message);
		}
	}
	
	public void traiterActionUnitaite(String action,MimeMessage message) throws Exception {
		String[]parametres = extractParametre(action);
		
		if (action.startsWith("flag-create")){
			log("traiter createFlag :" + (parametres!=null?parametres.length:"pas de parametres") );
			enregistrerMail(parametres,message);
		} else if (action.startsWith("mail")){
			log("traiter mail");
			envoyerMail(parametres, message);
			
		}else if (action.startsWith("sms"+ parametres)){
			log("traiter sms ");
			envoyerSMS(parametres,message);
		}
		
	}
	
	private void envoyerSMS(String[] parametres, MimeMessage message) throws Exception {
		for (String parametre : parametres) {
			System.out.println("envoie de sms vers : " + parametre);
			smsManager.sendMessage("0033660215004", parametre, "Un mail vient de vous parvenir. Sujet:"+ message.getSubject());
		}
	}

	private void envoyerMail(String[] parametres, MimeMessage message) throws AddressException, MessagingException {
		MimeMessage messageAEnvoyer = smtpManager.createMessage();
		for (String parametre : parametres) {
			messageAEnvoyer.setRecipient(RecipientType.TO,new  InternetAddress( parametre));
			messageAEnvoyer.setFrom(new InternetAddress(MailetGmdev.ADMIN));
			messageAEnvoyer.setText("Votre mail est bien arrivé " +
					 " a " + sdf.format(new Date()) + ".\n Le contenu a été classé dans Alfresco");
			
			//log("envoi message [to="+messageAEnvoyer.getRecipients(RecipientType.TO).toString()+ "]");
			smtpManager.sendMail(messageAEnvoyer);
		}
		

	}

	private void enregistrerMail(String[] parametres, MimeMessage message) throws MessagingException {
		
		for (String parametre : parametres) {

			log("enregistrer mail param:" + parametre + " message sujet:" + message.getSubject());
			
			parametre = parametre.replace("\"", "");
			StringBuilder sb = new StringBuilder();
			Address[] adresses = message.getFrom();
			for (Address address : adresses) {
				sb.append("from    : " + address.toString());
				sb.append(" , ");
			}
			sb.append("\n");
			Address[] adressesTo = message.getRecipients(RecipientType.TO);
			for (Address address : adressesTo) {
				sb.append("to      : " + address.toString());
			}
			sb.append("\n\n");
			Date dateReception = message.getReceivedDate();
			if (dateReception == null){
				dateReception = new Date();
			}
			sb.append(sdf.format(dateReception));
			sb.append("\n\n");
			sb.append("sujet : "+message.getSubject());
			System.out.println(sb.toString());
			
			log(" enregistrement pas ws ds alfreco nom fichier:" + parametre);
			log(" enregistrement pas ws ds alfreco texte:" + sb.toString());
			
			MailMessage mailMessage = new MailMessage(message);
			try {
				mailMessage.parse();
				
				String corps = mailMessage.getCorps();
				if (corps.toLowerCase().contains("<html>")){
					log("recuperation d u corps html");
					ContentReadAndWrite.addBinaryEntry(parametre+ "_corpsHTML", "text/html", corps.getBytes());
				} else {
					sb.append("/n/n");
					sb.append(corps);
				}
				
				List<PieceJointe> piecesJointes = mailMessage.getPiecesJointes();
				
				log("nb de pieces jointes sur le mail: " + piecesJointes.size());
				int nb = 0 ;
				String contentType = null ;
				for (PieceJointe pieceJointe : piecesJointes) {
					log("traitement pj nom:" + pieceJointe.getFilename() + " content type :" + pieceJointe.getContentType());
					if(pieceJointe.getContentType() != null){
						if (pieceJointe.getContentType().toLowerCase().contains("application/zip")){
							contentType = "application/zip";
						} else if (pieceJointe.getContentType().toLowerCase().contains("application/octet-stream")){
							contentType = "application/octet-stream";
						} else if (pieceJointe.getContentType().toLowerCase().contains("image/jpeg")){
							contentType = "image/jpeg";
						} else if (pieceJointe.getContentType().toLowerCase().contains("image/jpg")){
							contentType = "image/jpg";
						} else if (pieceJointe.getContentType().toLowerCase().contains("text/html")){
							contentType = "text/html";
						} else if (pieceJointe.getContentType().toLowerCase().contains("text/plain")){
							contentType = "text/plain";
						} else if (pieceJointe.getContentType().toLowerCase().contains("audio/caf")){
							contentType = "image/jpeg";
						} else if (pieceJointe.getContentType().toLowerCase().contains("video/quicktime")){
							contentType = "video/quicktime";
						} else if (pieceJointe.getContentType().toLowerCase().contains("text/plain")){
							contentType = "text/plain";
						}
						if (contentType != null ){
							ContentReadAndWrite.addBinaryEntry(parametre+ "_pj_" + pieceJointe.getFilename(), contentType, pieceJointe.getContenu());
							contentType = null ;
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ContentReadAndWrite.addEntry(parametre, sb.toString());
		}
	}

	private String[] extractParametre(String action) {
		String[] parameters = null ;
		if (action.contains("(") && action.contains(")")){
			String parametersString = action.substring(1+action.indexOf("("), action.indexOf(")"));
			parameters = parametersString.split(";");
		}
		return parameters;
	}
	
	public void setSmtpManager(SMTPManager smtpManager) {
		this.smtpManager = smtpManager;
	}

	public void setSmsManager(SMSManager smsManager) {
		this.smsManager = smsManager;
	}

	public MailetLogger getLogger() {
		return logger;
	}
	public void setLogger(MailetLogger logger) {
		this.logger = logger;
	}
	public void log(String message) {
		if (logger != null){
			logger.log(message);
		}else {
			System.out.println(message);
		}
	}
	public void log(String message, Throwable e) {
		if (logger != null){
			logger.log(message, e);
		} else {
			System.out.println(message);
			e.printStackTrace();
		}
	}



	public static void main(String[] args) throws IOException {
		System.setProperty("http.proxyHost", "vipproxy1.prod.extelia.fr");
		System.setProperty("http.proxyPort", "8080");
		LocalWorkFlowManager manager = new LocalWorkFlowManager();
		FileInputStream fis = null ;
		try {
			fis = new FileInputStream("/home/gilbert/Documents/test_gmx.eml");
			MimeMessage mm = new MimeMessage(null, fis);

			manager.traiterMail(mm);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			fis.close();
		}

		//		manager.traiterActions(" action=mail(gilbert@gmdev.fr;forgetdi@wanadoo.fr),flag-create(test_numero_1)");;
	}
}